from fastapi import params
from flask import Blueprint, current_app, request, jsonify, g
from flask_jwt_extended import jwt_required
from app.common.tool.direction import ensure_directories
from app.dao import user_dao
from app.common.md5.operate import get_md5
from app.common.jwt.operate import create_token

from app.common.custom import CustomResponse

user_routes = Blueprint('user', __name__)
  

@user_routes.route('/register', methods=['POST'])
def register_user():
  resp = CustomResponse('注册成功',200)
  try:
    params = request.get_json()
    # 检查是否有数据
    if not params:
        return jsonify({"error": "No JSON data provided"}), 400
    if not params.get('password'):
      resp = CustomResponse("密码不能为空", 500)
    if not params.get('username'):
      resp = CustomResponse("用户名不能为空", 500)
    if not all(params.get(key) for key in ['question1', 'question2', 'answer1', 'answer2']):
      resp = CustomResponse("密保信息不能为空", 500)
    if resp.code == 500:
      return jsonify(resp.to_dict()), 200
    user_param = {
      'username': params.get('username'),
      'password': get_md5(params.get('password')),
      'question1': params.get('question1'),
      'question2': params.get('question2'),
      'answer1': params.get('answer1'),
      'answer2': params.get('answer2'),
    }
    # 判断当前username是否有值
    userL = user_dao.select_user({'username': params.get('username')})
    if userL:
       resp = CustomResponse("该账号已被注册", 500)
       return jsonify(resp.to_dict()), 200
    isInsert = user_dao.insert_user(user_param)
    if isInsert == False:
      resp = CustomResponse("注册失败", 500)
    return jsonify(resp.to_dict()), 200
  except Exception as e:
        print(e)
        resp = CustomResponse("服务器异常", 500)
        return jsonify(resp.to_dict()), 200

@user_routes.route('/login', methods=['POST'])
def login():
  resp = CustomResponse('登录成功',200)
  try:
    params = request.get_json()
          
    # 检查是否有数据
    if not params:
        return jsonify({"error": "No JSON data provided"}), 400
    if not params.get('password'):
      resp = CustomResponse("密码不能为空", 500)
    if not params.get('username'):
      resp = CustomResponse("用户名不能为空", 500)
    if resp.code == 500:
      return jsonify(resp.to_dict()), 200
    user_param = {
      'username': params.get('username'),
      'password': params.get('password'),
    }
    # 密码加密
    userL = user_dao.select_user({'username': params.get('username')})
    if not userL:
       resp = CustomResponse('用户不存在', 500)
       return jsonify(resp.to_dict()), 200
    if get_md5(params.get('password')) != userL[0]['password']:
       resp = CustomResponse('密码错误', 500)
       return jsonify(resp.to_dict()), 200 
    token = create_token(userL[0]['id'])
    resp.data = {
       "token": token,
       "userInfo": userL[0]
    }
    # 登陆成功后需要查看data目录下面是否已经存在了该用户的文件夹
    ensure_directories(current_app.config['DATA_DIR'],userL[0]['id'])
    return jsonify(resp.to_dict()), resp.code
  except Exception as e:
        print(e)
        resp = CustomResponse('服务器错误', 500)
        return jsonify(resp.to_dict()), 200

@user_routes.route('/editPassword', methods=['PUT'])
def edit_password():
  resp = CustomResponse('修改成功',200)
  try:
    params = request.get_json()
          
    # 检查是否有数据
    if not params:
        return jsonify({"error": "No JSON data provided"}), 400
    if not params.get('username'):
      resp = CustomResponse("用户名不能为空", 500)
    if not params.get('answer1'):
      resp = CustomResponse("密保信息不能为空", 500)
    if not params.get('answer2'):
      resp = CustomResponse("密保信息不能为空", 500)
    if resp.code == 500:
      return jsonify(resp.to_dict()), 200
    # 密码加密
    userL = user_dao.select_user({'username': params.get('username')})
    if not userL:
       resp = CustomResponse('用户不存在', 500)
       return jsonify(resp.to_dict()), 200
    if userL[0]['answer1'] != params.get('answer1') or userL[0]['answer2'] != params.get('answer2'):
       resp = CustomResponse('密保信息错误', 500)
       return jsonify(resp.to_dict()), 200 
    userL[0]['password'] = get_md5("123456")
    isEdit = user_dao.update_user(userL[0])
    if not isEdit:
       resp = CustomResponse("修改失败", 500)
       return jsonify(resp.to_dict()), 200
    resp.data = {"password":"123456"}
    return jsonify(resp.to_dict()), resp.code
  except Exception as e:
        print(e)
        resp = CustomResponse('服务器错误', 500)
        return jsonify(resp.to_dict()), 200

@user_routes.route('/getSecretSecurity', methods=['POST'])
def get_secret_security():
  resp = CustomResponse('获取成功',200)
  try:
    params = request.get_json()
          
    # 检查是否有数据
    if not params:
        return jsonify({"error": "No JSON data provided"}), 400
    if not params.get('username'):
      resp = CustomResponse("用户名不能为空", 500)
    if resp.code == 500:
      return jsonify(resp.to_dict()), 200
    # 密码加密
    userL = user_dao.select_user({'username': params.get('username')})
    if not userL:
       resp = CustomResponse('用户不存在', 500)
       return jsonify(resp.to_dict()), 200
    user_po = {
       "username": userL[0]['username'],
       "question1": userL[0]['question1'],
       "question2": userL[0]['question2'],
    }
    resp.data = user_po
    return jsonify(resp.to_dict()), resp.code
  except Exception as e:
        print(e)
        resp = CustomResponse('服务器错误', 500)
        return jsonify(resp.to_dict()), 200



# # 读取上传的 MP3 文件为字节流
#     mp3_data = file.read()
    
#     # 使用 pydub 在内存中加载 MP3 数据
#     audio = AudioSegment.from_mp3(BytesIO(mp3_data))
    
#     # 设置采样率为 16000Hz
#     audio = audio.set_frame_rate(16000)

#     # 将转换后的音频数据导出为 WAV 格式，仍然保存在内存中
#     wav_io = BytesIO()
#     audio.export(wav_io, format='wav')
    
#     # 将字节流指针重置到开始
#     wav_io.seek(0)

#     # 使用 torchaudio 从内存加载 WAV 数据
#     waveform, sample_rate = torchaudio.load(wav_io)
    
#     # 处理采样率，如果不是 16000，进行重新采样
#     if sample_rate != 16000:
#         waveform = torchaudio.transforms.Resample(orig_freq=sample_rate, new_freq=16000)(waveform)
#         sample_rate = 16000

#     # 转换为 numpy 数组
#     audio_array = waveform.squeeze().numpy()
#     res = g.model.predict_stuttering(audio_array, sample_rate)

# # 读取上传的 MP3 文件为字节流
#     mp3_data = file.read()

#     # 使用 pydub 在内存中加载 MP3 数据
#     audio = AudioSegment.from_mp3(BytesIO(mp3_data))

#     # 设置采样率为 16000Hz
#     audio = audio.set_frame_rate(16000)

#     # 计算每个片段的时长（毫秒）
#     segment_length = len(audio) // 10  # 平均切割成 10 段

#     # 处理每个片段
#     results = []
#     for i in range(10):
#         start_time = i * segment_length
#         end_time = (i + 1) * segment_length if i < 9 else len(audio)  # 最后一段取完整长度
#         segment = audio[start_time:end_time]

#         # 将音频片段导出为 WAV 格式，仍然保存在内存中
#         wav_io = BytesIO()
#         segment.export(wav_io, format='wav')
#         wav_io.seek(0)

#         # 使用 torchaudio 从内存加载 WAV 数据
#         waveform, sample_rate = torchaudio.load(wav_io)

#         # 处理采样率，如果不是 16000，进行重新采样
#         if sample_rate != 16000:
#             waveform = torchaudio.transforms.Resample(orig_freq=sample_rate, new_freq=16000)(waveform)

#         # 转换为 numpy 数组
#         audio_array = waveform.squeeze().numpy()

#         # 进行口吃识别
#         res = g.model.predict_stuttering(audio_array, 16000)
#         for key, value in res.items():
#           print(f"Key: {key}, Value: {value}")
#         result = calculate_fluency(res['WordRep'], res['SoundRep'], res['Prolongation'], res['Block'], res['NoStutteredWords'], res['NaturalPause'], res['Interjection'])
#         results.append(result)